<template>
  <div>
    <customDialog
      :title="`添加剧目授权`"
      :dialogVisible="dialogVisible"
      @close="dialogVisible = false"
      :showFoot="false"
      width="800"
    >
      <div class="table_box_wrapper">
        <div class="batch_box">
          <el-button
            type="primary"
            size="small"
            @click.stop="handleBatch"
            :disabled="!selectionData.length"
          >
            {{ `批量授权` }}
          </el-button>
        </div>
        <custom-table
          :loading="loading"
          :columns="columns"
          :tableData="tableData"
          :pageObj="pageObj"
          @sizechange="sizechange"
          @currentChange="currentChange"
          :typeSelect="true"
          @selectionChange="selectionChange"
          :maxHeight="550"
          class="table_box"
        >
          <template #updateEpisodeNo="{ scope }">
            {{ `${scope.row?.updateEpisodeNo} / ${scope.row?.episodeNum}` }}
          </template>
          <template #promotionStartTime="{ scope }">
            <span v-if="activeTime(scope.row?.promotionStartTime)" class="red">
              {{
                moment(scope.row?.promotionStartTime + "Z").format(
                  "YYYY-MM-DD HH:mm:ss"
                )
              }}
            </span>
            <el-tag type="success" v-else>已开投</el-tag>
          </template>
          <template #operator="{ scope }">
            <el-button
              type="primary"
              size="small"
              @click.stop="handleAllocation(scope.row)"
            >
              {{ "授 权" }}
            </el-button>
          </template>
        </custom-table>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customTable from "@/components/CustomTable/index.vue";
import customDialog from "@/components/CustomDialog/index.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import { searchUnauthorized } from "@/api/operateCenter/distributorEpisode/index";
import { agentDistributor } from "@/api/operateCenter/episode/index";
import { ElTag, ElMessage } from "element-plus";
import { cloneDeep } from "lodash-es";
import moment from "moment";

const dialogVisible = ref(false);
const loading = ref<boolean>(false);
const selectionData = ref<Array<any>>([]);
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const form = {
  pageNo: 1,
  pageSize: 10,
  agentId: "",
  keyword: "",
};
const formData = ref(Object.assign({}, form));
const tableData = ref<Array<any>>([]);

const subData = reactive({
  tenantId: undefined,
  appId: undefined,
});

const columns = reactive([
  { prop: "operaId", label: "剧目Id", minWidth: 80 },
  { prop: "name", label: "剧目名称", minWidth: 120 },
  {
    prop: "promotionStartTime",
    label: "开投时间",
    slotName: "promotionStartTime",
    minWidth: 155,
  },
  {
    label: "已发布/总集数",
    prop: "updateEpisodeNo",
    slotName: "updateEpisodeNo",
    minWidth: 115,
  },
  { prop: "operator", slotName: "operator", label: "操作", width: 100 },
]);

// 批量操作
const handleBatch = () => {
  handleAllocation(selectionData.value);
};

// 分配
const emit = defineEmits(["success"]);
const handleAllocation = (val: any) => {
  // 如果为多选数组 则取 selectionData的值  否则取操作后面的单个数据 id
  if (!val) return;
  let ids = Array.isArray(val)
    ? selectionData.value.map((x: Record<string, any>) => {
        return Number(x.operaId);
      })
    : [Number(val.operaId)];
  let params = {
    operaIds: ids,
    agentIds: [formData.value.agentId],
  };
  agentDistributor(params).then(() => {
    dialogVisible.value = false;
    ElMessage.success(`授权成功`);
    emit("success");
  });
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = pageObj.pageNo;
  formData.value.pageSize = pageObj.pageSize;

  loading.value = true;
  searchUnauthorized(formData.value)
    .then((res: Record<string, any>) => {
      tableData.value = res?.data;
      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 多选
const selectionChange = (val: any) => {
  selectionData.value = val;
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

// 父级电子显示dialog
const showDialog = (val: any, str: string) => {
  // console.log("---显示分配分销商----**----", val);
  dialogVisible.value = true;
  formData.value.agentId = val;
  getList();
};

// 开投时间
const activeTime = (Time: string) => {
  let now = Date.now();
  let openTime = moment(Time).valueOf();
  return openTime > now ? true : false;
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.table_box_wrapper {
  margin-top: -15px;

  :deep(.table_content) {
    padding: 10px 0;
  }
}
</style>
